5.4 - How to execute something when a key is pressed?


To do something when a key is pressed we first need to add UnityEngine.InputLegacyModule.dll as a dll reference to our mod project. Then, since we are gonna change the player health when a key is pressed we also need to add Sons.dll which cointains infos about the player. After we have added the two needed dll references, we can start writing the mod.

Firs we need to include the Sons and UnityEngine namespace at the top of the code:


using SonsSdk;
using UnityEngine;
using Sons;

namespace GettingInput;
            

Then we need a section of code which executes constantly, so we can always listen for an input. For that, we will use the OnWorldUpdatedCallback method which constantly runs while we are loaded into a game.


public GettingInput()
{
    OnWorldUpdatedCallback = OnWorldUpdate;
    //HarmonyPatchAll = true;
}
    
// this method will loop indefinitely while we are in game
public void OnWorldUpdate()
{

}
            

Then, inside the OnWorldUpdate method we will write the code to get the user input:


public void OnWorldUpdate()
{
    if (Input.GetKeyDown(KeyCode.F2))
    {
        LocalPlayer.Vitals.SetHealth(100);
    }
}
            

Here, using an if statement, we are checking if the F2 key is pressed. If it is, the player health will be set to 100, otherwise nothing happens.

You can check the input for every key you want, just change the KeyCode to the key you want.

Examples


// setting the stamina to 100 when the T key is pressed

public void OnWorldUpdate()
{
    if (Input.GetKeyDown(KeyCode.T))
    {
        LocalPlayer.Vitals.SetStamina(100);
    }
}
            

// setting the stamina to 100 when the T key is released

public void OnWorldUpdate()
{
    if (Input.GetKeyUp(KeyCode.L))
    {
        LocalPlayer.Vitals.SetStamina(100);
    }
}